package com.example.save;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.save.R;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;


public class fragment3 extends Fragment {

    private Button writeInternalButton;
    private Button readInternalButton;
    private static final String FILE_NAME = "Ffile";

    public fragment3(){
        super(R.layout.fragment3);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {

        super.onViewCreated(view,savedInstanceState);

        writeInternalButton = getView().findViewById(R.id.writeExternalButton);

        writeInternalButton.setOnClickListener(new View.OnClickListener() {




            @Override
            public void onClick(View v) {
                try{
                    FileOutputStream os = getActivity().openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
                    BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(os));
                    writer.write("I am Tom");
                    writer.close();
                    Toast.makeText(getActivity(), "写入成功", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        readInternalButton=getView().findViewById(R.id.readExternalButton);
        readInternalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    try {
                        FileInputStream is=getActivity().openFileInput(FILE_NAME);
                        BufferedReader reader=new BufferedReader(new InputStreamReader(is));

                        String line=reader.readLine();

                        Toast.makeText(getActivity(), line, Toast.LENGTH_SHORT).show();

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

            }
        });

    }
}
